<template>
  <div class="inner-img-wrap" :class="className" ref="imgWrap">
    <img v-if="showImg" :src="url" alt="">
    <img v-if="!url && !showImg" src="../../../static/images/dangjian/dangwu/partyAffairs_bg_defalut.png">
  </div>
</template>

<script>
  export default {
    props: ['url'],
    name: 'bannerImg',
    data () {
      return {
        className: 'vertical',
        showImg: !false
      }
    },
    mounted () {
      this.preLoadImg(this.url)
    },
    methods: {
      preLoadImg (url) {
        if (!url) {
          return
        }
        let img = new Image()
        img.onload = () => {
          this.getClassName(img)
        }
        img.onerror = (...arg) => {
          this.showImg = true
        }
        img.src = url
        if (img.complete) {
          this.getClassName(img)
        }
      },
      getClassName (img) {
        this.showImg = true
        let el = this.$refs.imgWrap
        let h = el.clientHeight
        let w = el.clientWidth
        let oRatio = w / h
        let curRatio = img.width / img.height
        let className = oRatio > curRatio ? 'vertical' : 'horizontal'
        this.className = className
      }
    }
  }
</script>

<style scoped lang="scss">
  .inner-img-wrap {
    position: relative;
    width:100%;
    height:100%;
    overflow: hidden;
    background:url('../../../static/images/dangjian/dangwu/partyAffairs_bg_defalut.png') no-repeat center;
    background-size: 100% auto;
    img {
      position: absolute;
    }
    &.vertical {
      img {
        transform:translateY(-50%);
        top:50%;
        left:0;
        width:100%;
        height:auto;
      }
    }
    &.horizontal {
      img {
        transform:translateX(-50%);
        left:50%;
        top:0;
        width:auto;
        height:100%;
      }
    }
  }
</style>
